package com.vue.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vue.bean.R;
import com.vue.entity.ShoppingCartEntity;
import com.vue.entity.ShoppingCartEntity;
import com.vue.entity.ShoppingCartEntity;
import com.vue.entity.po.ShoppingCartPO;
import com.vue.entity.vo.ShoppingCartVO;
import com.vue.mapper.ShoppingCartMapper;
import com.vue.service.IShoppingCartService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜品购物车表 服务实现类
 * </p>
 *
 * @author wangruijie
 * @since 2024-08-04
 */
@Slf4j
@Service
@AllArgsConstructor
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCartEntity> implements IShoppingCartService {

    @Override
    public List<ShoppingCartVO> selectList(ShoppingCartPO po) {
        return baseMapper.selectVoList(po);
    }

    @Override
    public R addOrEditShoppingCart(ShoppingCartEntity po) {
        po.setMealDate(LocalDate.now());
        if (po.getId() == null){
            baseMapper.insert(po);
        }else {
            baseMapper.updateById(po);
        }
        return R.success("加到【已点】了");
    }

    @Override
    public R deleteById(Long id) {
        ShoppingCartEntity entity = baseMapper.selectById(id);
        if (entity == null){
            return R.fail("数据不存在");
        }
        removeById(id);
        return R.status(true);
    }

    @Override
    public R saveToMy(Long userId) {
        // 查询购物车数据列表
        ShoppingCartPO po = new ShoppingCartPO();
        po.setUserId(userId);
        po.setOrderFlag(0);
        List<ShoppingCartVO> vos = selectList(po);
        if (CollectionUtils.isEmpty(vos)){
            return R.status(true);
        }
        log.info("保存记录前查询购物车数据：{}", JSON.toJSON(vos));
        List<ShoppingCartEntity> entityList = new ArrayList<>();
        for (ShoppingCartVO vo:vos) {
            ShoppingCartEntity cartEntity = new ShoppingCartEntity();
            BeanUtils.copyProperties(vo, cartEntity);
            cartEntity.setOrderFlag(1);
            cartEntity.setMealDate(LocalDate.now());
            entityList.add(cartEntity);
        }
        updateBatchById(entityList);
        log.info("保存记录：{}", JSON.toJSON(entityList));
        return R.status(true);
    }

    @Override
    public R selectById(Long id) {
        return R.data(getById(id), "删除成功");
    }
}
